package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.MenuDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Menu;
import com.itheima.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service(interfaceClass = MenuService.class)
@Transactional
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuDao menuDao;

    /**
     * 查询所有菜单信息
     * @return
     */
    @Override
    public List<Menu> findAllRole() {
        return menuDao.findAllRole();
    }


    /**
     * 分页查询菜单信息
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<Menu> menuPage = menuDao.findPage(queryPageBean.getQueryString());
        return new PageResult(menuPage.getTotal(),menuPage.getResult());
    }

    /**
     * 查询所有父级菜单
     * @return
     */
    @Override
    public List<Menu> findAllParents() {
        return menuDao.findAllParents();
    }

    /**
     * 新增菜单信息
     * @param menu
     */
    @Override
    public void saveMenu(Menu menu) {
        menu.setLevel(2);
        menuDao.saveMenu(menu);
    }

    /**
     * 1.1：判断是否含有关联关系(t_role_menu)
     * 1.2：根据id删除菜单
     * @param id
     */
    @Override
    public Result deleteMenu(Integer id) {
       //1.1：判断是否含有关联关系
        Integer count = menuDao.selectRoleBymenuId(id);

        if(count > 0){
            return new Result(false, MessageConstant.DELETE_MENU_FAIL);
        }
        //1.2：根据id删除菜单
        boolean flag = menuDao.deleteMenu(id);
        return new Result(true, MessageConstant.DELETE_MENU_SUCCESS);
    }

    /**
     * 更新菜单信息
     * @param menu
     */
    @Override
    public void updateMenu(Menu menu) {
        menu.setLevel(2);
        menuDao.updateMenu(menu);
    }


    /**
     * 加载二级菜单
     * @param id
     * @return
     */
    @Override
    public List<Menu> findChildrensMenuById(Integer id) {
        return menuDao.findChildren(id);
    }
}
